package lambda;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantLockDemo {

    public static void main(String[] args) throws InterruptedException {


       /* for (int i = 0; i < 10; i++) {
            new Thread(()->{

                //lockObjSync(Thread.currentThread().getName());
                //lockObjReentlock(Thread.currentThread().getName());

            }).start();
        }*/

         new Thread(()->{
             try {
                 lockObjReentlockCond(Thread.currentThread().getName());
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         },"A").start();

         TimeUnit.SECONDS.sleep(5);

        new Thread(()->{


            reentrantLock.lock();
            condition_1.signalAll();
            reentrantLock.unlock();

        },"B").start();

    }


    public static ReentrantLock reentrantLock = new ReentrantLock();

    public static ReentrantReadWriteLock reentrantRdLock = new ReentrantReadWriteLock();

    public static Condition condition_1 = reentrantLock.newCondition();



    public static void lockObjReentlockCond(String threadName) throws InterruptedException {

        try{
            reentrantLock.lock();
            System.out.println(threadName + " 进入condition_1等待");
            condition_1.await();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println(threadName + " 解锁");
            reentrantLock.unlock();
        }

    }


    public static void lockObjReentlock(String threadName) throws InterruptedException {

        try{
            reentrantLock.lock();
            System.out.println(threadName);
            Thread.sleep(2000);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            reentrantLock.unlock();
        }

    }


    public synchronized static void lockObjSync(String threadName) throws InterruptedException {

        System.out.println(threadName);
        Thread.sleep(2000);

    }


}
